package com.mmall.service.impl;


import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.mmall.common.ServerResponse;
import com.mmall.dao.ShippingMapper;
import com.mmall.pojo.Shipping;
import com.mmall.service.IShippingService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author:lzq
 * @date: 2018/3/27 11:53
 */
@Service
public class ShipServiceImpl  implements IShippingService {

    @Autowired
    private ShippingMapper shippingMapper;


    public ServerResponse add(Integer userId, Shipping shipping){
        int count = shippingMapper.insert(shipping);
        if(count>0){
            //插入成功   需要把mybatis生成的主键返还给前端  更改一下mapper.xml配置即可
            Map resultMap=new HashMap();
            resultMap.put("shippingId",shipping.getId());
            return ServerResponse.createBySuccess("地址添加成功",resultMap);
        }
        return ServerResponse.createByErrorMessage("地址添加失败");
    }


    public ServerResponse upadte(Integer userId,Shipping shipping){
        //这里需要避免横向越权问题。即要保证当前用户更改的地址一定是自己的
        shipping.setUserId(userId);
        int count=shippingMapper.updateByShipping(shipping);
        if(count>0){
            return ServerResponse.createBySuccessMessage("地址更新成功");
        }
        return ServerResponse.createBySuccessMessage("地址更新失败");
    }

    public ServerResponse delete(Integer userId,Integer shippingId){
        int count=shippingMapper.deleteShipping(userId,shippingId);
        if(count>0){
            return ServerResponse.createBySuccess("地址删除成功");
        }
        return ServerResponse.createBySuccess("地址删除失败");
    }

    public ServerResponse select(Integer userId,Integer shippingId){
        Shipping shipping = shippingMapper.seleltByUserIdShippingId(userId, shippingId);
        if(shipping !=null){
            return ServerResponse.createBySuccess("地址信息获取成功",shipping);
        }
        return ServerResponse.createByErrorMessage("地址信息获取失败");
    }

    public ServerResponse list(Integer userId,int pageNum,int pageSize){
        PageHelper.startPage(pageNum,pageSize);
        List<Shipping> shippingList = shippingMapper.selectList(userId);
        PageInfo pageInfo=new PageInfo(shippingList);
        return ServerResponse.createBySuccess(pageInfo);
    }
}
